<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <el-steps :space="200" :active="active - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form label-position="top" label-width="80px" :rules="addGoodFormRule" :model="addGoodForm">
        <el-tabs :before-leave="beforeLeave" v-model="active" tab-position="left">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名" prop="goods_name">
              <el-input v-model="addGoodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量(kg)" prop="goods_weight">
              <el-input v-model="addGoodForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader @change="cascaderChg" v-model="addGoodForm.goods_cat" :options="options"
                :props="props"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 复选框 -->
            <!-- 复选框 -->
            <el-form-item :label="t1.attr_name" v-for="t1 in attrMany" :key="t1.attr_id">
              <el-checkbox-group v-model="t1.attr_vals">
                <el-checkbox border :label="t2" v-for="(t2, index) in t1.attr_vals" :key="index"> </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 多个输入框 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in attrOnly" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片上传的ip地址不经过request的,所以需要自己写好路径list-type文件列表的类型text/picture/picture-card
            headers设置请求头 -->
            <el-upload class="upload-demo" action="http://127.0.0.1:8888/api/private/v1/upload" list-type="picture-card"
              :headers="headers" :on-success="onSuccessImg" :on-preview="onPreviewImg" :on-remove="onRemoveImg">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <div slot="tip" class="el-upload__tip div_box">只能上传jpg/png文件,且不超过500KB</div>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <div class="editor">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
                :mode="mode" @onCreated="handleCreated" />
            </div>
            <el-button class="submit" type="primary" @click="AddGood">添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 显示图片dialog -->
    <el-dialog title="图片预览" v-model="dialogVisibleImg" width="50%">
      <img style="width: 100%;" :src="previewImgUrl" alt="" srcset="">
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from '@/util/request'
import { ElMessage } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const mode = 'default'
const active = '0'
const previewImgUrl = ref('')
// 商品属性,静态参数
const attrOnly = ref([])
const dialogVisibleImg = ref(false)
// 图片的请求头
const headers = ref({})
// 校验信息,属性名字必须一样 form校验规则
const addGoodFormRule = {
  goods_name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  goods_price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  goods_weight: [
    { required: true, message: '请输入商品数量', trigger: 'blur' }
  ],
  goods_number: [
    { required: true, message: '请输入商品数量', trigger: 'blur' }
  ],
  goods_cat: [
    { required: true, message: '请输入商品数量', trigger: 'blur' }
  ]
}
const props = {
  expandTrigger: 'hover',
  label: 'cat_name',
  value: 'cat_id'
}
const options = ref([])
// 保存表单信息
const addGoodForm = {
  goods_name: '',
  goods_price: 0,
  goods_weight: 0,
  goods_number: 0,
  goods_introduce: '',
  // 商品分类
  goods_cat: [],
  pics: []
}
// 分类的属性,动态参数
const attrMany = ref([])
// tabclick点击的时候触发
const beforeLeave = (activeName, oldActiveName) => {
  // console.log(activeName, oldActiveName);
  // 3可以放行, "0"
  if (!(activeName === "0" || addGoodForm.goods_cat.length === 3)) {
    ElMessage.error("请选择商品分类")
    // 给出提示
    return false
  }
  // 获取分类的参数
  if (activeName === "1") {
    getCategoriesAttr()
  }
  // 获取商品属性
  if (activeName === "2") {
    getCategoriesAttrOnly()
  }
  // 上传图片
  if (activeName === "3") {
    headers.value.Authorization = sessionStorage.getItem("token")
  }
}
// 获取商品参数
const getCategoriesAttr = async () => {
  const { data, meta } = await request({
    url: `/categories/${addGoodForm.goods_cat[2]}/attributes`,
    params: {
      sel: 'many'
    },
    method: "GET"
  })
  if (meta.status !== 200) {
    return ElMessage.error("获取分类参数错误")
  }
  // data是数组
  // console.log(data);
  data.forEach(obj => {
    obj.attr_vals = obj.attr_vals.split(" ")
    // 新田的数据,手动勾选
    obj.attr_arr = []
  });
  attrMany.value = data
}
// 静态的参数
const getCategoriesAttrOnly = async () => {
  const { data, meta } = await request({
    url: `/categories/${addGoodForm.goods_cat[2]}/attributes`,
    params: {
      sel: 'only'
    },
    method: "GET"
  })
  if (meta.status !== 200) {
    return ElMessage.error("商品属性获取错误")
  }
  console.log(data);
  attrOnly.value = data
}
// 级联选择器改变的时候触发
const cascaderChg = () => {
  if (addGoodForm.goods_cat.length !== 3) {
    addGoodForm.goods_cat = []
  }
  console.log("改变了");
}
// 获取分类数组
const getCategoriesArr = async () => {
  const { data, meta } = await request({
    url: "/categories",
    method: "GET"
  })
  if (meta.status !== 200) {
    return ElMessage.error('获取分类失败')
  }
  options.value = data
  // console.log(data);
}
// 添加商品
const AddGood = async () => {
  // 添加商品参数
  addGoodForm.attrs = []
  attrMany.value.forEach((obj) => {
    const attr_id = obj.attr_id;
    const attr_value = obj.attr_vals.join(" ");
    addGoodForm.attrs.push({ attr_id, attr_value })
  })
  // 商品参数
  attrOnly.value.forEach((obj) => {
    const attr_id = obj.attr_id;
    const attr_value = obj.attr_vals
    addGoodForm.attrs.push({ attr_id, attr_value })
  })
  // 商品属性
  addGoodForm.goods_cat = addGoodForm.goods_cat.join(",")
  // 提交数据
  const { meta } = await request({
    url: "/goods",
    method: "POST",
    data: addGoodForm
  })
  if (meta.status !== 201) {
    return ElMessage.error("添加失败")
  }
  // 跳转商品列表
  // this.$router.push("/home/goods")
  router.push({ name: "goods" })
}
const onSuccessImg = (response, file, fileList) => {
  // console.log(response);
  // console.log(file);
  const obj = { pic: response.data.tmp_path, uid: file.uid }
  addGoodForm.pics.push(obj)
}
const onPreviewImg = (file) => {
  // 对话框显示
  dialogVisibleImg.value = true
  // 图片赋值
  previewImgUrl.value = file.response.data.url
}
const onRemoveImg = (file, fileList) => {
  // console.log(file);
  // console.log(fileList);
  // 通过uid 找下标
  const i = addGoodForm.pics.findIndex((item) => {
    return item.uid === file.uid
  })
  // console.log(i);
  addGoodForm.pics.splice(i, 1)
}
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = '<p></p>'
  }, 1500)
})

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
onMounted(() => {
  getCategoriesArr()
})
</script>

<style scoped>
.el-card {
  margin-top: 20px;
}

.el-steps {
  margin-left: 190px;
  margin-top: 10px;
}

.div_box {
  margin-top: 100px;
  width: 300px;
}
.editor{
  border: 1px solid #ccc;
}
</style>
